import React, { useMemo, useState } from "react";
import { Button, Form, Input, Space, Table, Image, message, Modal } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import type { ColumnsType } from 'antd/es/table';
import { accountFundTypes, receivableBillTypes } from "@/constants/types";
import { calculateTableWidth, downloadFile } from "@/utils/util";
import { useComponentDidMount } from "@/hooks";
import { useRequest } from "ahooks";
import { billList, billTabNum, billAdd, billBatchConfirm, billUpdate, billBatchExport, billSingleExport, billWriteOff } from "../services";
import XlRadio from "@/components/Form/XlRadio";
import XlTableDictColumn from "@/components/Table/XlTableDictColumn";
import { Link } from "@umijs/max";
import BillBatchPay from "../modals/BillBatchPay";
import BillPay from "../modals/BillPay";
import MakeUpBill from "../modals/MakeUpBill";
import BillUpdate from "../modals/BillUpdate";

const {Item} = Form;
const isAll = (status: any) => !status || status === 'all';
const isDraf = (status: string | number) => +status === 1;
const isConfirm = (status: string | number) => +status === 2;
const isPay = (status: string | number) => +status === 3;
const isPaied = (status: string | number) => +status === 4;
const isOv = (status: string | number) => +status === 5;

const ReceivableBill = () => {
  const [form] = Form.useForm();

  //
  const [visible, setVisible] = useState(false);
  const { loading: addLoading, runAsync: addApi} = useRequest(billAdd, {manual: true});

  //
  const [updateVisible, setUpdateVisible] = useState(false);
  const { loading: updateLoading, runAsync: updateApi} = useRequest(billUpdate, {manual: true});


  const statusMaps: any [] = [
    {
      label: "全部",
      value: "all",
      num: "totalNum"
    },
    {
      label: "草稿",
      value: "1",
      num: "draftNum"
    },
    {
      label: "待确认",
      value: "2",
      num: "waitConfirmedNum"
    },
    {
      label: "待核销",
      value: "3",
      num: "waitWriteOffNum"
    },
    {
      label: "已核销",
      value: "4",
      num: "writtenOffNum"
    },
    {
      label: "逾期",
      value: "5",
      num: "overDueNum"
    },
  ];

  // order status 
  const [status, setStatus] = useState<string>('all');
  const [tabNumObj, setTabNumObj] = useState<any>({});

  const [dataSource, setDataSource] = useState([]);
  const [pagination, setPagination] = useState({
    total: 0,
    pageNum: 1,
    pageSize: 20
  });

  //
  const [selectedRowKeys, setSelectedRowKeys] = useState<string []>([]);
  // const [selectedRows, setSelectedRows] = useState<receivableBillTypes []>([]);
  const [currentRow, setCurrentRow] = useState<receivableBillTypes | null>(null);
  // 
  const {loading: billPayLoading, runAsync: billPayApi} = useRequest(billBatchConfirm, {manual: true});
  const [billPayVisible, setBillPayVisible] = useState(false);
  const [batchBillPayVisible, setBatchBillPayVisible] = useState(false);

  
  const getParams = () => {
    const params = form.getFieldsValue();
    return {
      ...params
    }
  }
  const resetSelectedRows = () => {
    setSelectedRowKeys([]);
  }

  const fetchTabNumApi = async (params: any = {}) => {
    const res = await billTabNum({
      ...params,
    });
    setTabNumObj(res || {});
  }
  
  const search = async (params: any) => {
    const res = await billList({
      ...params,
      status: params?.status === "all" ? undefined : params.status
    });
    setDataSource(res?.data || []);
    setPagination({
      total: res?.total,
      pageNum: res?.pageNum,
      pageSize: res?.pageSize
    });
  }

  const refreshData = () => {
    const params = getParams();
    search({
      ...params,
      status,
      pageNum: 1,
      pageSize: 20
    });
    fetchTabNumApi(params);
  }

  // 新增
  const addProps = {
    title: "补录账单",
    loading: addLoading,
    visible,
    onCancel: () => {
      setVisible(false);
    },
    onSubmit: async (params: any) => {
      const res = await addApi(params);
      if (res?.code === "0") {
        addProps.onCancel();
        refreshData();
      }
      
    }
  }
  // 编辑
  const updateProps = {
    title: "更新账单",
    currentRow,
    loading: updateLoading,
    visible: updateVisible,
    onCancel: () => {
      setUpdateVisible(false);
      setCurrentRow(null);
    },
    onSubmit: async (params: any) => {
      const res = await updateApi(params);
      if (res?.code === "0") {
        updateProps.onCancel();
        refreshData();
      }
      
    }
  }
  
  // 批量确认
  const handleBatchConfirm = () => {
    if (!selectedRowKeys?.length) {
      message.warning("请选择数据");
      return ;
    }
    Modal.confirm({
      title: "温馨提示",
      content: "是否确认账单数据无误？",
      onOk: () => {
        billBatchConfirm({
          ids: selectedRowKeys
        }).then(
          res => {
            if (res?.code === '0') {
              refreshData();
            }
          }
        )
      }
    });
  }
  const handleBillConfirm = (record: receivableBillTypes) => {
    Modal.confirm({
      title: "温馨提示",
      content: "是否确认账单数据无误？",
      onOk: () => {
        billBatchConfirm({
          ids: [record?.id]
        }).then(
          res => {
            if (res?.code === '0') {
              refreshData();
            }
          }
        )
      }
    });
  }
  // 批量标记付款
  const batchBillPayProps = {
    visible: batchBillPayVisible,
    selectedRowKeys: selectedRowKeys,
    loading: billPayLoading,
    title: "批量标记付款",
    onCancel: () => {
      setBatchBillPayVisible(false);
      resetSelectedRows();
    },
    onSubmit: async (params: any) => {
      const res = await billWriteOff(params);
      if (res?.code === "0") {
        batchBillPayProps.onCancel();
        refreshData();
      }
    }
  }
  // 标记付款
  const billPayProps = {
    visible: billPayVisible,
    currentRow: currentRow,
    loading: billPayLoading,
    title: "标记付款",
    onCancel: () => {
      setBillPayVisible(false);
      setCurrentRow(null);
    },
    onSubmit: async (params: any) => {
      const res = await billWriteOff(params);
      if (res?.code === "0") {
        billPayProps.onCancel();
        refreshData();
      }
    }
  }

  const handleBillBatchPay = () => {
    if (!selectedRowKeys?.length) {
      message.warning("请选择数据");
      return ;
    }
    setBatchBillPayVisible(true);
  }
  const handleBillPay = (record: receivableBillTypes) => {
    setCurrentRow(record);
    setBillPayVisible(true);
  }

  const handleBatchExport = () => {
    if (!selectedRowKeys?.length) {
      message.warning("请选择数据");
      return ;
    }
    Modal.confirm({
      title: "温馨提示",
      content: "是否确认导出账单？",
      onOk: () => {
        billBatchExport({ids: selectedRowKeys}).then(
          res => {
            if (res) {
              downloadFile(res);
            }
          }
        )
      }
    });
  }
  const handleExport = (record: receivableBillTypes) => {
    Modal.confirm({
      title: "温馨提示",
      content: "是否确认导出账单？",
      onOk: () => {
        billSingleExport({id: record?.id}).then(
          res => {
            if (res) {
              downloadFile(res);
            }
          }
        )
      }
    });
    
  }
  // 编辑
  const handleEdit = (record: receivableBillTypes) => {
    setCurrentRow(record);
    setUpdateVisible(true);
  }
  // 新建
  const handleAdd = () => {
    setVisible(true);
  }
  

  // status change
  const handleStatusChange = (val: any) => {
    const params = getParams();
    setStatus(val?.value);
    resetSelectedRows();
    search({
      ...params,
      status: val?.value,
      pageNum: 1,
      pageSize: 20
    });
    fetchTabNumApi();
  }


  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: string [], rows: receivableBillTypes []) => {
      setSelectedRowKeys(keys);
      // setSelectedRows(rows);
    },
  }


  const columns: ColumnsType<accountFundTypes> = [
    {
      title: "应收单号",
      dataIndex: "billCode",
      width: 160,
      fixed: 'left',
      render: (_, record) => {
        return <Link to={`/finance-manage/receivable-bill-detail?billId=${record?.id}`}>{record?.billCode}</Link>
      }
    },
    {
      title: "状态",
      dataIndex: "status",
      width: 100,
      render: (_, record) => <XlTableDictColumn value={record?.status} type="billStatus" />
    },
    {
      title: "客户简称",
      dataIndex: "customerName",
      width: 150,
      ellipsis: true
    },  
    {
      title: "账单金额/元",
      dataIndex: "amount",
      width: 120
    },
    {
      title: "应付金额/元",
      dataIndex: "leftAmount",
      width: 120
    },
    {
      title: "币种",
      dataIndex: "currency",
      width: 100
    },
    {
      title: "结算方式",
      dataIndex: "settlementMethod",
      width: 140,
    },
    {
      title: "业务时间",
      dataIndex: "businessTime",
      width: 180
    },
    {
      title: "所属销售",
      dataIndex: "salesName",
      width: 120
    },
    {
      title: "所属客服",
      dataIndex: "serviceName",
      width: 120
    },
    {
      title: "备注",
      dataIndex: "remark",
      width: 150,
      ellipsis: true
    },
    {
      title: "操作",
      dataIndex: "options",
      width: 220,
      fixed: 'right',
      render: (_, record) => {
        return (
          <Space>
            {isDraf(record?.status) && <Button type="link" onClick={() => handleEdit(record)}>编辑账单</Button>}
            {isDraf(record?.status) && <Button type="link" onClick={() => handleExport(record)}>导出账单</Button>}
            {(isPay(record?.status) || isOv(record?.status)) && <Button type="link" onClick={() => handleBillPay(record)}>标记已付款</Button>}
            {isConfirm(record?.status) && <Button type="link" onClick={() => handleBillConfirm(record)}>确认账单</Button>}
          </Space>
        );
      }
    },
  ];

  const newColumns: ColumnsType<accountFundTypes> = [...columns];
  if (isOv(status)) {
    newColumns.splice(5, 0,  {
      title: "已支付",
      dataIndex: "payAmount",
      width: 120
    },)
    newColumns.splice(6, 0,  {
      title: "逾期天数",
      dataIndex: "overDueDay",
      width: 100
    },)
  }
  if (isPaied(status)) {
    newColumns.pop();
  }

  const composeOrderStatusMaps = useMemo(() => {
    return statusMaps.map(v => ({
      ...v,
      label: tabNumObj?.[v?.num] > 0 ? `${v?.label} (${tabNumObj?.[v?.num]})` : v.label
    }))
  }, [JSON.stringify(tabNumObj), JSON.stringify(statusMaps)]);

  const handleSearch = () => {
    const params = getParams();
    search({
      ...params,
      status,
      pageNum: 1,
      pageSize: 20
    });
    fetchTabNumApi(params);
  }
  const handleReset = () => {
    form.resetFields();
    search({
      status,
      pageNum: 1,
      pageSize: 20
    });
  }

  useComponentDidMount(() => {
    search({
      pageNum: 1,
      pageSize: 20
    });
    fetchTabNumApi();
  })

  return (
    <>
      <Form form={form} layout="inline">
        <Item label="应收单号" name="billCode" style={{marginBottom: 15}}>
          <Input />
        </Item>
        <Item label="公司简称" name="customerName" style={{marginBottom: 15}}>
          <Input onPressEnter={handleSearch} />
        </Item>
        
        <Space style={{marginBottom: 20}}>
          <Button type="primary" onClick={handleSearch}>查询</Button>
          <Button type="default" onClick={handleReset}>重置</Button>
        </Space>
      </Form>
      <div style={{display: 'flex', justifyContent:'space-between', flexWrap: 'wrap'}}>
        <div >
          <XlRadio.ButtonRadioGroup value={status} onChange={(val: string []) => handleStatusChange(val)} options={composeOrderStatusMaps} />
        </div>
        <Space style={{display: 'flex', justifyContent: 'flex-end', }}>
          {isDraf(status) && <Button type="primary" onClick={handleBatchExport}><PlusOutlined />批量导出账单</Button>}
          {(isDraf(status) || isAll(status)) && <Button type="primary" onClick={handleAdd}><PlusOutlined />补录账单</Button>}
          {isConfirm(status) && <Button type="primary" onClick={handleBatchConfirm}><PlusOutlined />批量确认账单</Button>}
          {(isPay(status) || isOv(status)) && <Button type="primary" onClick={handleBillBatchPay}><PlusOutlined />批量标记付款</Button>}
        </Space>
      </div>
      <Table
        className="mt10"
        rowKey="id"
        bordered
        dataSource={dataSource}
        columns={newColumns}
        scroll={{x: calculateTableWidth(columns), y: 580}}
        rowSelection={rowSelection}
        pagination={{
          showTotal: (total: number) => `共 ${total} 条`,
          ...pagination,
          onChange: (pageNum, pageSize) => {
            const params = getParams();
            search({
              ...params,
              pageNum,
              pageSize
            });
          }
        }}
      />
      {visible && <MakeUpBill {...addProps} />}
      {updateVisible && <BillUpdate {...updateProps} />}
      {batchBillPayVisible && <BillBatchPay {...batchBillPayProps} />}
      {billPayVisible && <BillPay {...billPayProps} />}
    </>
  );
}
export default ReceivableBill;